#!/bin/bash

# ----------------------------------------------------------------------
# Filename:   tftp_start.sh
# Version:    1.0
# Date:       2013/05/15
# Author:      huijing.hei
# Email:       huijing.hei@cs2c.com.cn
# Summary:     02系统基本功能-04网络服务-02tftp-01启动服务
# Notes:       ***
# Copyright:    China Standard Software Co., Ltd.
# History：     
#             Version 1.0, 2013/05/15
#             - Start tftp service.
# ----------------------------------------------------------------------

function setup_config()
{

    # tftp configure file: /etc/xinetd.d/tftp
    TFTP_CONF=""

    if [ -r "/etc/xinetd.d/tftp" ];then
       TFTP_CONF="/etc/xinetd.d/tftp"
    else
       echo "/etc/xinetd.d/tftp not exists, program end."
       exit 1
    fi

    # backup configure file
    [ ! -z "${TFTP_CONF}" ] && cp "${TFTP_CONF}" "${TFTP_CONF}.bak"

    # set disable = no
    DISABLE=$(awk -F "=" '/[[:space:]]disable/{print $2}' $TFTP_CONF | tr -d ' ')

    if [ "${DISABLE}" = "yes" ];then
        sed -i 's/\(disable[[:space:]]*=[[:space:]]*\)yes/\1no/' $TFTP_CONF
        echo "set disable = no."
    fi
   
    # get tftp server default directory
    SERVER_ARGS=$(awk -F "=" '/server_args/{print $2}' $TFTP_CONF | tr -d " ")
    [ ${SERVER_ARGS:0:2} = "-s" ] && SERVER_DIR=$(echo $SERVER_ARGS | tr -d "\-s")

    chmod -R 777 ${SERVER_DIR}

    # append -c with server_args
    echo "set server_args, append -c."
    sed -i "s#$SERVER_DIR#& -c#" $TFTP_CONF
    [ $? -eq 0 ] && echo "setup $TFTP_CONF."
}

function service_daemon()
{
    #retart xinetd
        if command -v systemctl >/dev/null 2>&1; then
            HAVE_SYSTEMCTL=1
        else
            HAVE_SYSTEMCTL=0
        fi
    # check systemctl
        if [ $HAVE_SYSTEMCTL -eq 1 ]; then
                com="/bin/systemctl $2 $1.service"
        else
                com="/sbin/service $1 $2"
        fi

    case "$2" in
        start)
            eval "$com"
            sleep 3
            netstat -ap | grep tftp
            [ $? -ne 0 ] && { echo "testcase tftp start fail."; exit 1; }
            ;;
        stop)
            eval "$com"
            sleep 3
            netstat -ap | grep tftp
            [ $? -eq 0 ] && { echo "testcase tftp stop fail."; exit 1; }
            ;;
        restart)
            eval "$com"
            sleep 3
            netstat -ap | grep tftp
            [ $? -ne 0 ] && { echo "testcase tftp restart fail."; exit 1; }
            ;;
       *)
            echo "pls check"
            ;;
    esac
            
}

function cleanup()
{
    mv -f "${TFTP_CONF}.bak" "${TFTP_CONF}"
    
    return 0
}


setup_config
service_daemon xinetd restart
#cleanup
